package net.tycmc.bulb.note.core.Util;

import java.util.List;
import java.util.Map;

import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;
import com.baidu.yun.push.auth.PushKeyPair;
import com.baidu.yun.push.client.BaiduPushClient;
import com.baidu.yun.push.constants.BaiduPushConstants;
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.baidu.yun.push.model.PushMsgToSingleDeviceRequest;
import com.baidu.yun.push.model.PushMsgToSingleDeviceResponse;

public class MsgTobaidyun {

	public void sendMsg(List<Map<String,Object>> list,Map<String,Object> configMap, String apiKey, String secretKey){
        /*
         * @brief 推送单播通知(Android Push SDK拦截并解析) message_type = 1 (默认为0)
         */
        // 1. 设置developer平台的ApiKey/SecretKey
        //String apiKey = MapGetter.getString(configMap,"apiKey");
        //String secretKey = MapGetter.getString(configMap,"secretKey");
      //获取频道id
		String channelId="" ;
		//获取手机端userid
		String userId = "";
		//获取产生故障的设备号
		String vehicleNumber = "";
		//获取故障码
		String fltCode = "";
		//获取故障详情
		String fltDetial = "";
		//获取风险信息
		String riskSuggest = "";
		//拼接标题
		String title = "";
		//故障发生时间
		String msgtime="";
		//推送类型
		String type = "";
		//故障等级1、2、3、4
		String level="";
		//拼接内容
		String description = fltDetial+";"+riskSuggest;
		//要发送的内容
		String sendMsg="";
		//发送语言环境1：英文，0：中午
		String lan = "";
		
        PushKeyPair pair = new PushKeyPair(apiKey, secretKey);

        // 2. 创建BaiduPushClient，访问SDK接口
        BaiduPushClient pushClient = new BaiduPushClient(pair,BaiduPushConstants.CHANNEL_REST_URL);

        // 3. 若要了解交互细节，请注册YunLogHandler类
        // 3. 注册YunLogHandler，获取本次请求的交互信息
        pushClient.setChannelLogHandler (new YunLogHandler () {
            @Override
            public void onHandle (YunLogEvent event) {
                System.out.println(event.getMessage());
            }
        });

       

        	//遍历list集合
        	for(int i = 0; i < list.size(); i++){
        		
        		Map<String, Object> msgData = list.get(i);
        		lan=msgData.get("lan").toString();
        		//获取频道id
        		channelId =msgData.get("chanlid").toString();
        		//获取手机端userid
        		userId = (String) msgData.get("userid");
        		//获取产生故障的设备号
        		vehicleNumber = (String) msgData.get("vehiclenumber");
        		//获取故障码
        		fltCode = (String) msgData.get("fltcode");
        		//获取故障详情
        		if(lan.equals("1")){//英文
        			fltDetial = (String) msgData.get("fltdetialmsg_EN");
        			//拼接标题
            		title = vehicleNumber+"Fault"+fltCode;
            		riskSuggest = (String) msgData.get("risk_EN");
        		}else{
        			fltDetial = (String) msgData.get("fltdetialmsg");
        			//拼接标题
            		title = vehicleNumber+"故障"+fltCode;
            		//获取风险信息
            		riskSuggest = (String) msgData.get("risk");
        		}
        		//故障时间
        		msgtime=(String) msgData.get("msgtime");
        		//拼接内容
        	    description = fltDetial+";"+riskSuggest+";"+msgtime;
        		//推送类型
        		type = "1";
        		//故障等级
        		level=(String) msgData.get("level");
        		//发送内容
        		//sendMsg="{'title':'"+title+"','description':'"+description+"','type':'"+type+"','level':'"+level+"','msgtime':'"+msgtime+"'}";
        		sendMsg="{\"title\":\""+title+"\",\"description\":\""+description+"\"}";
        	    //如果channelId和userId有一个为空则进行下一次循环
        		if(channelId.equals("") || channelId==null || userId.equals("") || userId==null){
        			continue;
        		}
	            // 4. 创建请求类对象
	            // 手机端的ChannelId， 手机端的UserId， 先用1111111111111代替，用户需替换为自己的
        		 PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest();
        		 request.addChannelId(channelId);
        		 request.addMsgExpires(new Integer(3600));   //设置消息的有效时间,单位秒,默认3600*5.
        		 request.addMessageType(1);
                 request.addMessage(sendMsg);             //设置消息类型,0表示透传消息,1表示通知,默认为0.
                 request.addDeviceType(3);      //设置设备类型，deviceType => 1 for web, 2 for pc, 
                                         //3 for android, 4 for ios, 5 for wp.
	
                 try {
              // 5. 执行Http请求
                 PushMsgToSingleDeviceResponse response = pushClient.
                     pushMsgToSingleDevice(request);
	            // 6. 认证推送成功
                 System.out.println("msgId: " + response.getMsgId()+ ",sendTime: " + response.getSendTime());
        	 } catch (PushClientException e) {
                 //ERROROPTTYPE 用于设置异常的处理方式 -- 抛出异常和捕获异常,
                 //'true' 表示抛出, 'false' 表示捕获。
                 if (BaiduPushConstants.ERROROPTTYPE) { 
                     try {
     					throw e;
     				} catch (PushClientException e1) {
     					// TODO Auto-generated catch block
     					e1.printStackTrace();
     				}
                 } else {
                     e.printStackTrace();
                 }
			} catch (PushServerException e) {
				if (BaiduPushConstants.ERROROPTTYPE) {
					try {
						throw e;
					} catch (PushServerException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				} else {
					System.out
							.println(String
									.format("requestId: %d, errorCode: %d, errorMsg: %s",
											e.getRequestId(), e.getErrorCode(),
											e.getErrorMsg()));
				}
			}
        	}
       
	}
}
